
package com.compuvest.feed

class DataFeed {

    def nextLink

    def parseFeed(xml) {

        def feed
        try {
            feed = new XmlSlurper().parseText(xml).declareNamespace(sc: 'http://schemas.google.com/structuredcontent/2009')
        }
        catch(e) {
            println ">>>>>>DataFeed::parseFeed() Bad XML file <<<<<<xml=[${xml}]"
            return
        }
        //println 'feed=' << feed

        nextLink = null // reset

        feed.link.each{ link ->
            if(link.@rel.text() == 'next') {
                nextLink = link.@href.text()
            }
        }
        //println 'next=' << next

        def accwareCode, entities = [:]
        feed.entry.each { entry ->
            accwareCode = entry.'sc:id'.text()

            entities[accwareCode] =
                new Entity(
                    field: [
                        expdate:    entry.'sc:expiration_date'.text(),
                        nextlink:   nextLink
                    ]
                )
        }
        //println 'entities=' << entities

	return entities
    }

    def getNextLink() {
        return nextLink
    }

    def makeBatch(items) {

        //println "items=" << items

        def feed = new StringBuilder()
        feed << "<?xml version='1.0' encoding='UTF-8'?>\n"
        feed << "<feed xmlns='http://www.w3.org/2005/Atom'"
        feed << " xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/'"
        feed << " xmlns:app='http://www.w3.org/2007/app'"
        feed << " xmlns:sc='http://schemas.google.com/structuredcontent/2009'"
        feed << " xmlns:scp='http://schemas.google.com/structuredcontent/2009/products'"
        feed << " xmlns:batch='http://schemas.google.com/gdata/batch'>\n"

        items.each { accwareid, item ->

            switch(item.action['type']) {
                case 'insert':
                    feed << getInsertEntry(accwareid, item)
                    break
                case 'update':
                    feed << getUpdateEntry(accwareid, item)
                    break
                case 'query':
                    feed << getQueryEntry(accwareid)
                    break
                case 'delete':
                    feed << getDeleteEntry(accwareid)
                    break
            } // switch
        } // each

        feed << "</feed>"

        return feed
    }

    def getInsertEntry(accwareid, item) {

        def xml = new StringBuilder()
        xml << "<entry>\n"
        xml << " <batch:operation type='insert'/>\n"
        xml << " <title>${item.field['name']}</title>\n"
        xml << " <content>${item.field['name']}</content>\n"
        xml << " <link rel='alternate' type='text/html' "
        xml << "href='http://www.compuvest.com/Search.jsp?Search="
        xml << "${item.field['mfrnumber']}&amp;advsite=froogle&amp;sku=${accwareid}&amp;dp="
        xml << "${item.field['qty']}:${item.field['vendorname']}:${(item.field['reslprice'].toDouble() * 100).round()}:${item.field['drone']}:${item.field['older']}'/>\n"
        xml << " <sc:id>${accwareid}</sc:id>\n"
        xml << " <sc:image_link>http://img.compuvest.com/0/${accwareid}.jpg</sc:image_link>\n"
        xml << " <sc:content_language>en</sc:content_language>\n"
        xml << " <sc:target_country>US</sc:target_country>\n"
//        xml << " <scp:author>compuvest.com</scp:author>\n"
        xml << " <scp:availability>in stock</scp:availability>\n"
        xml << " <scp:brand>${item.field['mfrname']}</scp:brand>\n"
        xml << " <scp:condition>${item.field['condition']}</scp:condition>\n"
        xml << " <scp:google_product_category>${item.field['catname']}</scp:google_product_category>\n"
        xml << " <scp:product_type>${item.field['catname']}</scp:product_type>\n"
        xml << " <scp:manufacturer>${item.field['mfrname']}</scp:manufacturer>\n"
        xml << " <scp:mpn>${item.field['mfrnumber']}</scp:mpn>\n"
        xml << " <scp:adwords_labels>${item.field['accwareid']}</scp:adwords_labels>\n"
        xml << " <scp:adwords_grouping>${item.field['googlegroup']}</scp:adwords_grouping>\n"
        xml << " <scp:price unit='USD'>${item.field['sellprice']}</scp:price>\n"
        if(item.field['upc'] != '0') {
            xml << " <scp:gtin>${item.field['upc']}</scp:gtin>\n"
        }
        xml << " <scp:quantity>${item.field['qty']}</scp:quantity>\n"
        xml << " <scp:shipping_weight unit='lb'>${item.field['weight']}</scp:shipping_weight>\n"
        xml << " </entry>\n"

        return xml
    }

    def getUpdateEntry(accwareid, item) {

        def xml = new StringBuilder()
        xml << "<entry>\n"
        xml << " <batch:operation type='update'/>\n"
        xml << " <id>https://content.googleapis.com/content/v1/100115/items/products/generic/${accwareid}</id>\n"
        xml << " <title>${item.field['name']}</title>\n"
        xml << " <content>${item.field['name']}</content>\n"
        xml << " <link rel='alternate' type='text/html' "
        xml << "href='http://www.compuvest.com/Search.jsp?Search="
        xml << "${item.field['mfrnumber']}&amp;advsite=froogle&amp;sku=${accwareid}&amp;dp="
        xml << "${item.field['qty']}:${item.field['vendorname']}:${(item.field['reslprice'].toDouble() * 100).round()}:${item.field['drone']}:${item.field['older']}'/>\n"
        xml << " <sc:id>${accwareid}</sc:id>\n"
        xml << " <sc:image_link>http://img.compuvest.com/0/${accwareid}.jpg</sc:image_link>\n"
        xml << " <sc:content_language>en</sc:content_language>\n"
        xml << " <sc:target_country>US</sc:target_country>\n"
        xml << " <scp:availability>in stock</scp:availability>\n"
        xml << " <scp:brand>${item.field['mfrname']}</scp:brand>\n"
        xml << " <scp:condition>${item.field['condition']}</scp:condition>\n"
        xml << " <scp:google_product_category>${item.field['catname']}</scp:google_product_category>\n"
        xml << " <scp:product_type>${item.field['catname']}</scp:product_type>\n"
        xml << " <scp:manufacturer>${item.field['mfrname']}</scp:manufacturer>\n"
        xml << " <scp:mpn>${item.field['mfrnumber']}</scp:mpn>\n"
        xml << " <scp:adwords_labels>${item.field['accwareid']}</scp:adwords_labels>\n"
        xml << " <scp:adwords_grouping>${item.field['googlegroup']}</scp:adwords_grouping>\n"
        xml << " <scp:price unit='USD'>${item.field['sellprice']}</scp:price>\n"
        if(item.field['upc'] != '0') {
            xml << " <scp:gtin>${item.field['upc']}</scp:gtin>\n"
        }
        xml << " <scp:quantity>${item.field['qty']}</scp:quantity>\n"
        xml << " <scp:shipping_weight unit='lb'>${item.field['weight']}</scp:shipping_weight>\n"
        xml << "</entry>\n"

        return xml
    }


    def getDeleteEntry(accwareid) {

        def xml = new StringBuilder()
        xml << "<entry>\n"
        xml << " <batch:operation type='delete'/>\n"
        xml << " <id>https://content.googleapis.com/content/v1/100115/items/products/generic/${accwareid}</id>\n"
        xml << "</entry>\n"

        return xml
    }

    def getQueryEntry(accwareid) {

        def xml = new StringBuilder()
        xml << "<entry>\n"
        xml << " <batch:operation type='query'/>\n"
        xml << " <id>https://content.googleapis.com/content/v1/100115/items/products/generic/${accwareid}</id>\n"
        xml << "</entry>\n"

        return xml
    }

    def parseResult(xml, items) {

        //println "\n>>>xml:\n${xml.toString()}"
        def result = 'Error'
        def feed
        try {
            feed = new XmlParser().parseText(xml.toString())
        }
        catch(e) {
            println ">>>>>>DataFeed::parseResult() Bad XML file <<<<<<xml=[${xml}]"
            return result
        }
        //println "feed=${feed}"

        def type, googleid, googlesku, item//, out = new StringBuilder()
        feed.entry.each { entry ->
            type = entry.'batch:operation'.@type[0]

            //out << "type=${type} "
            switch(type) {
                case 'insert':
                case 'update':
                case 'query':
                    googlesku = entry.'sc:id'.text()
                    break
                case 'delete':
                    googleid = entry.id.text()
                    googlesku = googleid[googleid.lastIndexOf('/') + 1..-1]
                    break
            } // switch

            //out << "googlesku=${googlesku} code=${entry.'batch:status'.@code[0]} reason=${entry.'batch:status'.@reason[0]}\n"
            result = "googlesku=${googlesku} code=${entry.'batch:status'.@code[0]} reason=${entry.'batch:status'.@reason[0]}"
            if(googlesku) {
                item = items[googlesku]
                item.status['code'] = entry.'batch:status'.@code[0]
                item.status['reason'] = entry.'batch:status'.@reason[0]
            }
        }
        //println out

        return result
    }

    def showResult(items, count) {

        def result = [:], res = new StringBuilder()
        result['insert'] = 0
        result['update'] = 0
        result['delete'] = 0

        items.each { accwareid, item ->

            switch(item.action['type']) {
                case 'insert':
                    result['insert']++
                    break
                case 'update':
                    result['update']++
                    break
                case 'delete':
                    result['delete']++
                    break
            } // switch

            res << "<tr>"
            res << "<td>${count++}</td><td>${accwareid}</td><td>\$${item.field['oldreslprice']} : \$${item.field['reslprice']}</td>"
            res << "<td>\$${item.field['oldsellprice']} : \$${item.field['sellprice']}</td>"
            res << "<td>${item.action['type']}</td><td>${item.status['code']}</td><td>${item.status['reason']}</td><td>${item.status['accware']}</td>"
            res << "</tr>"
        }
        result['html'] = res.toString()

        return result
    }
}

